﻿using MettingOrder.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;

namespace MettingOrder.Controllers
{
    public class MettingController : BaseApiController
    {
        /// <summary>
        /// 返回所有的设备
        /// </summary>
        /// <returns></returns>
        public Result GetEquiment()
        {
            var list = db.Query<Equipment>("where 1=1");
            return JsonHelper.Success(list);
        }
        /// <summary>
        /// 返回所有的本门
        /// </summary>
        /// <returns></returns>
        public Result GetDepartment(int departmentId)
        {
            var departmentList = db.Query<Department>("where 1=1").ToList(); //所有的部门集合
            var d = departmentList.FirstOrDefault(s => s.Id == departmentId);
            if (d != null)
            {
                d.IsChecked = true;

                //将所有的父级的
                var parentId = d.ParentId;
                while (parentId != 0)
                {
                    d = departmentList.FirstOrDefault(s => s.Id == parentId);
                    if (d != null)
                        d.IsChecked = true;
                    parentId = d.ParentId;
                }
            }
            return JsonHelper.Success(departmentList.Select(s => new
            {
                s.Name,
                s.IsChecked,
                s.Id,
                s.OrderId,
                s.ParentId,
            }));
        }
        /// <summary>
        /// 感觉设计的并不好,不如全部换成多对对吧,如果你觉得有必要的话
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Result GetDeparmtn_Employee()
        {
            var departmentIds = HttpContext.Current.Request.QueryString["departmentIds"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (departmentIds == null) return JsonHelper.Success();
            StringBuilder sb = new StringBuilder();
            int index = 0;
            List<object> objList = new List<object>();
            foreach (var item in departmentIds)
            {
                sb.AppendFormat("select * from Employee where charindex(@{0},departmentId)>0 union all ", index++);
                objList.Add("," + item + ",");
            }
            var sql = sb.ToString().Substring(0, sb.Length - 10);

            var list = db.Query<Employee>(sql, objList.ToArray());
            
            return JsonHelper.Success(list);
        }
        public Result AddMetting(Metting model)
        {
            if (model.StartDate > model.EndDate)
            {
                return JsonHelper.Error("开会时间必须比结束时间早");
            }

            return JsonHelper.Success();
        }
    }

    public class GetDepartMentResult
    {

    }
}